/*
 *
 *	UFO ATTACK
 *	game script by irvan fanani
 *	02 Juli 2012
 *
 */

var ufo = new Object();
ufo.life = 3;
ufo.score = 0;
ufo.level = 0;
ufo.levelUp = [2000,6000,12000,24000,50000];
ufo.bulletSpeed = 5;


//set enemies
ufo.enemy = new Object();
ufo.enemy.no1 = new Object();
ufo.enemy.no1.speed = 1;
ufo.enemy.no1.countOut = 0;
ufo.enemy.no1.countOut2 = 0;
ufo.enemy.no1.countOutMax = 500;
ufo.enemy.no1.obj = function() {
   var x = 500
   var y = (Math.random()*300)+50;
   /*
   this.x = 900
   this.y = (Math.random()*300)+50;
    this.draw = function() {
		this.x -= 1
		jaws.context.drawImage(jaws.assets.get("assets/musuh1.png"), this.x, this.y)
		if(this.collision){
			this.remove()
		}
    }
	*/
	var sprite = new jaws.Sprite({image: "assets/musuh1.png", x: x, y: y, anchor: "center"})
    enemys.push(sprite)
}	

function PlayState() {
      var player
      var bullets = []
	  var enemys = []
	  var bulletsEnemy = []

      this.setup = function() {
        player = new jaws.Sprite({image: "assets/jagoan.png", x: 10, y:100, anchor:"center"})
        player.can_fire = true
        jaws.on_keydown("esc",  function() { jaws.switchGameState(MenuState) })
        jaws.preventDefaultKeys(["up", "down", "left", "right", "space"])
      }

      this.update = function() {
	  
        if(jaws.pressed("left"))  { player.x -= 2;player.angle = -10; }
        if(jaws.pressed("right")) { player.x += 2;player.angle = 10; }
        if(jaws.pressed("up"))    { player.y -= 2;player.angle = -10; }
        if(jaws.pressed("down"))  { player.y += 2;player.angle = 10; }
        if(jaws.pressed("space")) { 
          if(player.can_fire) {
            //bullets.push( new Bullet(player.rect().right, player.y) )
            
			var x = player.rect().right
			var y = player.y
			var sprite = new jaws.Sprite({image: "assets/pelor.png", x: x, y: y, anchor: "center"})
			bullets.push(sprite)
			
			player.can_fire = false
            setTimeout(function() { player.can_fire = true }, 700)
          }
        }

        forceInsideCanvas(player)
        //bullets.removeIf(isOutsideCanvas) // delete items for which isOutsideCanvas(item) is true
		//enemys.removeIf(enemyIsOutsideCanvas)

		player.angle /= 1.10
		
		//SET MUSUH KELUAR
		ufo.enemy.no1.countOut++
		if(ufo.enemy.no1.countOut >= (ufo.enemy.no1.countOutMax - (ufo.level*100))){
			ufo.enemy.no1.countOut = 0;
			var x = 800
			var y = (Math.random()*300)+50;
			var sprite = new jaws.Sprite({image: "assets/musuh1.png", x: x, y: y, anchor: "center"})
			sprite.fireMax = 150 + (Math.random()*150)
			sprite.fireCount = sprite.fireMax;
			enemys.push(sprite)
		}
		ufo.enemy.no1.countOut2 += 1.5
		if(ufo.enemy.no1.countOut2 >= (ufo.enemy.no1.countOutMax - (ufo.level*100))){
			ufo.enemy.no1.countOut2 = 0;
			var x = 800
			var y = (Math.random()*300)+50;
			var sprite = new jaws.Sprite({image: "assets/musuh1.png", x: x, y: y, anchor: "center"})
			sprite.fireMax = 150 + (Math.random()*150)
			sprite.fireCount = sprite.fireMax;
			enemys.push(sprite)
		}
		
		//SET TUMBUKAN
		jaws.collideOneWithMany(player,enemys).forEach( function(pair, index) {
		  enemys.splice(index,1); 
        });
		jaws.collideManyWithMany(enemys,bullets).forEach( function(pair, index) {
			pair[0].collision = true
			pair[1].collision = true
			ufo.score = ufo.score + 100
        });
		
		//SET LEVEL
		if(ufo.score > ufo.levelUp[ufo.level]){
			ufo.level += 1;
		}
      
	  }

      this.draw = function() {
        jaws.context.clearRect(0,0,jaws.width,jaws.height)
        player.draw()
        //bullets.draw()  // will call draw() on all items in the list
		//enemys.draw()
		
		setScore(ufo.score)
		
		enemys.forEach( function(sprite, index) {
			sprite.fireCount++
			if(sprite.fireCount >= sprite.fireMax){
				sprite.fireCount = 0
				var x = sprite.x - 20
				var y = sprite.y
				var sprite = new jaws.Sprite({image: "assets/pelor.png", x: x, y: y, anchor: "center"})
				bulletsEnemy.push(sprite)
			}
          sprite.x -= ufo.enemy.no1.speed
		  //sprite.removeIf(enemyIsOutsideCanvas)
		  if(sprite.collision){
			enemys.splice(index,1);		  
		  }
		  sprite.draw()
        });
		bullets.forEach( function(sprite, index) {
          sprite.x += ufo.bulletSpeed
		  
		  if(sprite.collision){
			bullets.splice(index,1);		  
		  }
		  sprite.draw()
        });
		bulletsEnemy.forEach( function(sprite, index) {
          sprite.x -= 2
		  sprite.draw()
        });
		
      }

      /* Simular to example1 but now we're using jaws properties to get width and height of canvas instead */
      /* This mainly since we let jaws handle the canvas now */
      function isOutsideCanvas(item) { 
        return (item.x < 0 || item.y < 0 || item.x > jaws.width || item.y > jaws.height) 
      }
	  function enemyIsOutsideCanvas(item) { 
        return (item.x < -50 || item.y < -50 || item.y > jaws.height+150) 
      }
      function forceInsideCanvas(item) {
        if(item.x - (item.width/2) < 0)                  { item.x = item.width/2  }
        if(item.x + item.width > jaws.width)     { item.x = jaws.width - item.width }
        if(item.y < 0)                  { item.y = 0 }
        if(item.y + item.height  > jaws.height)  { item.y = jaws.height - item.height }
      }

      function Bullet(x, y) {
        this.x = x
        this.y = y-15
        this.draw = function() {
          this.x += 4
          jaws.context.drawImage(jaws.assets.get("assets/pelor.png"), this.x, this.y)
        }
      }
	  
	  function setScore(score){
		jaws.context.font = "bold 12pt arial";
          jaws.context.fillStyle =  "Black"
          jaws.context.strokeStyle =  "rgba(200,200,200,0.0)"
          jaws.context.fillText('score: '+score, 10, 15)
		  
		  jaws.context.font = "bold 12pt arial";
          jaws.context.fillStyle =  "Black"
          jaws.context.strokeStyle =  "rgba(200,200,200,0.0)"
          jaws.context.fillText('level: '+ufo.level, 600, 15)
	  }

    }

    /*
    *
    * MenuState is our lobby/welcome menu were gamer can chose start, high score and settings.
    * For this example we have only implemented start. Start switches active game state by simply:
    *   jaws.switchGameState(play)   (jaws.switchGameState(PlayState) would have worked too)
    *
    */
    function MenuState() {
      var index = 0
      var items = ["Start", "Settings", "Highscore"]

      this.setup = function() {
        index = 0
        jaws.on_keydown(["down","s"],       function()  { index++; if(index >= items.length) {index=items.length-1} } )
        jaws.on_keydown(["up","w"],         function()  { index--; if(index < 0) {index=0} } )
        jaws.on_keydown(["enter","space"],  function()  { if(items[index]=="Start") {jaws.switchGameState(PlayState) } } )
      }

      this.draw = function() {
        jaws.context.clearRect(0,0,jaws.width,jaws.height)
        for(var i=0; items[i]; i++) {
          // jaws.context.translate(0.5, 0.5)
          jaws.context.font = "bold 24pt arial";
          jaws.context.lineWidth = 10
          jaws.context.fillStyle =  (i == index) ? "Red" : "Black"
          jaws.context.strokeStyle =  "rgba(200,200,200,0.0)"
          jaws.context.fillText(items[i], 30, 100 + i * 60)
        }  
      }
    }

    /*
    *
    * Our script-entry point
    *
    */
    window.onload = function() {
      jaws.assets.add("assets/jagoan.png")
      jaws.assets.add("assets/pelor.png")
	  jaws.assets.add("assets/musuh1.png")
      jaws.start(MenuState)
    }